package cn.wetcland.es.controller;

import cn.wetcland.es.dto.LoginDTO;
import cn.wetcland.es.dto.StudentLoginDTO;
import cn.wetcland.es.dto.TeacherLoginDTO;
import cn.wetcland.es.service.EsStudentService;
import cn.wetcland.es.service.EsTeacherService;
import cn.wetcland.es.utils.MyAssert;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    private EsStudentService studentService;

    @Resource
    private EsTeacherService teacherService;

    @RequestMapping("/commonLogin")
    public String login(LoginDTO loginDTO, HttpSession session) {
        Object o = verifyLoginParam(loginDTO);
        if (o instanceof StudentLoginDTO) {
            studentLogin((StudentLoginDTO) o, session);
        } else if (o instanceof TeacherLoginDTO) {
            teacherLogin((TeacherLoginDTO) o, session);
        }
        return "redirect:/";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/";
    }

    public Object verifyLoginParam(LoginDTO loginDTO) {
        MyAssert.isTrue(loginDTO.getRole() != null && (loginDTO.getRole()==1||loginDTO.getRole()==2||loginDTO.getRole()==3), "登录角色有误");
        MyAssert.notBlank(loginDTO.getUsername(), "请输入用户名");
        MyAssert.notBlank(loginDTO.getPassword(), "请输入密码");
        if (loginDTO.getRole() == 1) {
            StudentLoginDTO studentLoginDTO = new StudentLoginDTO();
            studentLoginDTO.setStudentSno(loginDTO.getUsername());
            studentLoginDTO.setPassword(loginDTO.getPassword());
            return studentLoginDTO;
        } else if (loginDTO.getRole() == 2) {
            TeacherLoginDTO teacherLoginDTO = new TeacherLoginDTO();
            teacherLoginDTO.setTeacherTno(loginDTO.getUsername());
            teacherLoginDTO.setPassword(loginDTO.getPassword());
            return teacherLoginDTO;
        }
        MyAssert.isTrue(false, "验证错误");
        return null;
    }

    @RequestMapping("/studentLogin")
    public String studentLogin(StudentLoginDTO loginDTO, HttpSession session) {
        studentService.login(loginDTO, session);
        return "redirect:/";
    }

    @RequestMapping("/teacherLogin")
    public String teacherLogin(TeacherLoginDTO teacherLoginDTO, HttpSession session) {
        teacherService.login(teacherLoginDTO, session);
        return "redirect:/";
    }

}
